package com.adnaan.backend.service.impl;

import com.adnaan.backend.entity.Dishes;
import com.adnaan.backend.entity.DishesSteps;
import com.adnaan.backend.entity.dto.DosageDto;
import com.adnaan.backend.entity.vo.DosageVo;
import com.adnaan.backend.mapper.DishesMapper;
import com.adnaan.backend.service.DishesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * author: adnaan
 * create: 2025-02-19 13:09
 * Description:
 */
@Service
@Slf4j
public class DishesServiceImpl extends ServiceImpl<DishesMapper, Dishes> implements DishesService {

    @Override
    public List<Dishes> getDishesByHerbalId(Long herbalId) {
        // 通过关联表查询包含指定药材的药膳
        return baseMapper.selectDishesByHerbalId(herbalId);
    }

    @Override
    public List<DishesSteps> getStepsByDishId(Long dishId) {
        return baseMapper.getSteps(dishId);
    }

    @Override
    public List<DosageDto> getMaterialsByDishId(Long dishId) {
        return baseMapper.getDosage(dishId);
    }

    @Override
    public List<DishesSteps> getSteps(Long id) {
        return baseMapper.getSteps(id);
    }

    @Override
    public List<DosageDto> getDosage(Long id) {
        return baseMapper.getDosage(id);
    }

    @Transactional
    @Override
    public boolean addMaterial(DosageVo dosages) {
        // 先删除dishesId下所有
        baseMapper.deleteDosage(dosages.getDishId());
        List<DosageVo.MedicinalDosage> dosageList = dosages.getDosage();
        if (!dosageList.isEmpty()) {
            try {
                // 再添加
                dosageList.forEach(item -> {
                    baseMapper.addMaterial(dosages.getDishId(), item.getMaterialId(), item.getDosage());
                });
                return true;
            } catch (Exception e) {
                // 记录异常信息
                log.error("Failed to add materials for dishId: {}", dosages.getDishId(), e);
                throw e; // 抛出异常，让事务管理器处理回滚
            }
        } else {
            // 记录日志，提示剂量列表为空
            log.info("Dosage list is empty for dishId: {}", dosages.getDishId());
            return false;
        }
    }

    @Override
    public boolean deleteMaterial(Long dishId, Long materialId) {
        return baseMapper.deleteMaterial(dishId, materialId);
    }

    @Override
    public boolean saveSteps(DishesSteps dishesSteps) {
        if (dishesSteps.getId() == null) {
            return baseMapper.insertStep(dishesSteps);
        }
        return baseMapper.updateStep(dishesSteps);
    }

    @Override
    public boolean sortDishSteps(List<DishesSteps> dishesSteps) {
        // 先删除所有步骤
        baseMapper.deleteSteps(dishesSteps.get(0).getDishId());
        // 再添加
        dishesSteps.forEach(item -> {
            baseMapper.insertStep(item);
        });
        return true;
    }
}
